/*
 *  molFile.c
 *  testProject
 *
 *  Created by Christoph Seitz on 14.04.08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "molFile.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

mld * prasemolfile(char * file) {
	FILE *f = fopen(file,"r");
	char *n = "1234567890";
	char *buf=malloc(2*sizeof(char)),*ret=malloc(2*sizeof(char)),*temp=malloc(6*sizeof(char));
	mld *m;
	mldfile *mm;
	int i=0,c=0,line = 0,j=0,k=0;
	if (f != NULL ) {
		ret = fgets(buf,2,f);
		if (ret == NULL) {printf("Error: Empty File!"); return NULL;}
		while ( *ret != '\n') {
			*(temp+i) = *ret;
			++i;
			ret = fgets(buf,2,f);
		}
		*(temp+i)='\000';
		if ( (int)strspn(temp,n) != i) {
			printf("Error: Mol size not defined!");
			return NULL;
		}
		c = (int)atof(temp);
		m = malloc((c+1)*sizeof(mld));
		mm = malloc(c*sizeof(mldfile));
		temp= malloc(5);
		i=0;
		while ( ret !=NULL) {
			//ID
			ret = fgets(buf,2,f);
			if (ret == NULL) break;
			i=0;
			do {
				*(temp+i) = *ret;
				++i;
				ret = fgets(buf,2,f);
			} while (*ret!=' ');
			*(temp+i) = '\000';
			if ( (int)strspn(temp,n) != i) {
				printf("Error: In line %i",line+2);
				return NULL;
			}
			(mm+line)->uid=(int)atof(temp);
			i=0;
			ret = fgets(buf,2,f);
			//name
			do {
				*(temp+i) = *ret;
				++i;
				ret = fgets(buf,2,f);
			} while (*ret!=' ');
			*(temp+i) = '\000';
			strcpy(&(mm+line)->m[0],temp);
			strcpy(&(m+line)->m[0],temp);
			//bindings
			for (i=0;i<4;++i) {
				(mm+line)->bn[i][0] =0;
				(mm+line)->bn[i][1] =0;
			}
			for (j=0;j<4;++j) {
				for (k=0;k<2;++k) {
					i=0;
					ret = fgets(buf,2,f);
					do {
						*(temp+i) = *ret;
						++i;
						ret = fgets(buf,2,f);
					} while ((((*buf!=' ') && (*buf!='\n'))&&((*buf!=' ') || (*buf!='\n')))&&ret!=NULL);
					if (k==0 && *ret=='\n') {
						printf("Error: In line %i",line+2);
						return NULL;
					}
					*(temp+i) = '\000';
					if ( (int)strspn(temp,n) != i) {
						printf("Error: In line %i",line+2);
						return NULL;
					}
					(mm+line)->bn[j][k]=(int)atof(temp);
					if (*buf=='\n' || ret==NULL) break;
				}
				if (*buf=='\n' || ret==NULL) break;
			}
			++line;
		}
		int p;
		for (k=0;k<line;++k) {
			p=0;
			for(j=0;j<4;++j) (m+k)->bn[j]=NULL;
			for(j=0;j<4;++j) { 
				if((mm+k)->bn[j][1]==1) {
				(m+k)->bn[p+j+0]=m+(mm+k)->bn[j][0]-1;
				}
				if((mm+k)->bn[j][1]==2 && j<3) {
					(m+k)->bn[p+j+0]=m+(mm+k)->bn[j][0]-1;
					(m+k)->bn[p+j+1]=m+(mm+k)->bn[j][0]-1;
					p=1;
				} else {printf("ERROR:");};
				if((mm+k)->bn[j][1]==3 && j<2) {
					(m+k)->bn[p+j+0]=(m+(mm+k)->bn[j][0])-1;
					(m+k)->bn[p+j+1]=(m+(mm+k)->bn[j][0])-1;
					(m+k)->bn[p+j+2]=(m+(mm+k)->bn[j][0])-1;
					p=2;
				}else {printf("ERROR:");}
			}
		}
	}
	(m+c)->m[0]='E';
	free(buf);free(ret);free(temp);free(mm);
	return m;
}